package com.eryos.gwt.estate.core.service.impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.eryos.gwt.estate.core.service.ConfigService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * GreetingService implementation.
 * 
 * @author combeol
 * @version $Revision$
 */
@Service("configService")
public class ConfigServiceImpl extends RemoteServiceServlet implements ConfigService {

    /** Generated serialVersionUID. */
    private static final long serialVersionUID = 4405927377128006232L;

    /** The Logger. */
    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigServiceImpl.class);

    private static final String CONFIGURATION_FILE = "config/config.properties";
    private static final String CONFIGURATION_CHARSET = "UTF-8";

    @Override
    public String getApplicationVersion() {
        LOGGER.debug("<getApplicationVersion>");

        String result = "";
        Properties props = new Properties();
        InputStreamReader is = null;
        try {
            LOGGER.debug("Loading file <{}> using charset <{}>", CONFIGURATION_FILE, CONFIGURATION_CHARSET);
            is =
                    new InputStreamReader(Thread.currentThread().getContextClassLoader()
                            .getResourceAsStream(CONFIGURATION_FILE), Charset.forName(CONFIGURATION_CHARSET));
            props.load(is);

        } catch (FileNotFoundException e) {
            LOGGER.error("Configuration file not found <" + CONFIGURATION_FILE + "> ", e);
            return e.getMessage();
        } catch (IOException e) {
            LOGGER.error("IOException while loading configuration file <" + CONFIGURATION_FILE + ">", e);
            return e.getMessage();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                LOGGER.error("InputStream can not be closed", e);
            }
        }

        if (props.containsKey("applicationName")) {
            result = props.getProperty("applicationName");
        }
        if (props.containsKey("applicationVersion")) {
            result += " v" + props.getProperty("applicationVersion");
        }
        if (props.containsKey("applicationBuild")) {
            result += " (#" + props.getProperty("applicationBuild");
        }
        if (props.containsKey("applicationRevision")) {
            result += "-" + props.getProperty("applicationRevision") + ")";
        }
        if (props.containsKey("applicationDate")) {
            result += " - " + props.getProperty("applicationDate");
        }

        return result;
    }
}
